/**
 * Copyright 2010 Nicholas Alexander Cross
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dataporter.io.csv;

import org.apache.log4j.Logger;
import org.csvreader.CsvWriter;
import org.dataporter.data.DataLogEntry;
import org.dataporter.data.DataUpdate;
import org.dataporter.io.DataWriter;
import org.dataporter.io.EntitySink;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CSVDataWriter<Sink extends EntitySink<? extends OutputStream>> implements DataWriter<Sink> {

    private static final Logger logger = Logger.getLogger( CSVDataWriter.class );

    private final Map<String, CsvWriter> writers = new HashMap<String, CsvWriter>();

    private EntitySink<?extends OutputStream> sink;

    public void init( Sink sink ) throws Exception {
        this.sink = sink;
    }

    private CsvWriter getWriter( String entityName, Set<String> headers ) throws IOException {
        CsvWriter csvWriter = writers.get( entityName );

        if ( csvWriter == null )
        {
            csvWriter = initWriter( entityName, headers );
        }

        return csvWriter;
    }

    protected CsvWriter initWriter( String entityName, Set<String> headers ) throws IOException {
        CsvWriter csvWriter = new CsvWriter( sink.sinkForEntity( entityName ), ',', Charset.forName( "UTF-8" ) );

        for ( String header : headers )
        {
            csvWriter.write( header );
        }

        csvWriter.endRecord();

        writers.put( entityName, csvWriter );
        return csvWriter;
    }

    public DataLogEntry write( DataUpdate object ) {
        try
        {
            CsvWriter writer = getWriter( object.getEntityName(), object.getChanges().keySet() );
            Map<String, Object> map = object.getChanges();
            Collection<Object> objects = map.values();

            for ( Object o : objects )
            {
                writer.write( String.valueOf( o ), true );
            }

            writer.endRecord();

            return new DataLogEntry( object.getEntityName(), object.getChanges() );

        }
        catch ( IOException e )
        {
            logger.error( "Failed to write data", e );
            return new DataLogEntry( "Failed to write data with exception: " + e.getClass().getName() + " - " + e.getMessage() );
        }
    }

    public void close() {
        for ( CsvWriter writer : writers.values() )
        {
            try
            {
                writer.close();
            }
            catch ( Exception e )
            {
                logger.error( "Failed to close csv writer", e );
            }
        }

        writers.clear();
    }

}
